﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace AiMei.Redis.Core
{
    public class Utils
    {
        private static int ReadIndex { get; set; }

        private static int WriteIndex { get; set; }
        static Utils()
        {
            TaskQueue1 = new ConcurrentQueue<TaskCompletionSource<RedisObject>>();
            TaskQueue2 = new ConcurrentQueue<TaskCompletionSource<RedisObject>>();
        }
        private static ConcurrentQueue<TaskCompletionSource<RedisObject>> TaskQueue1 { get; set; }
        private static ConcurrentQueue<TaskCompletionSource<RedisObject>> TaskQueue2 { get; set; }


        public static void Enqueue(TaskCompletionSource<RedisObject> task)
        {
            unchecked { ++WriteIndex; }
            if (WriteIndex % 2 == 0)
            {
                TaskQueue1.Enqueue(task);
            }
            else
            {
                TaskQueue2.Enqueue(task);
            }
        }

        public static bool TryDequeue(out TaskCompletionSource<RedisObject> result)
        {
            unchecked { ++ReadIndex; }
            if (ReadIndex % 2 == 0)
            {
                return TaskQueue1.TryDequeue(out result);
            }
            else
            {
                return TaskQueue2.TryDequeue(out result);
            }
        }
    }
}
